package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JasonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;
    /**
     * 用户登录的接口
     * 资源：/sessions
     * 参数：email  password
     * 动作：post
     */
    @PostMapping
    public Object saveSession(@RequestParam String email, @RequestParam String password){
        //创建一个jsonResult对象
        JasonResult js = new JasonResult();
        try{
            //调用登录的业务逻辑方法
            User u = userService.login(email,password);
            //需要将当前登录成功的用户设置到sesssion中去
            UserContext.setCurrentUser(u);
            //登录成功之后还要设置在json中，返回结果
            js.setData(u);
        }catch(Exception e){
            js.mark(e.getMessage());
        }
        return js ;
    }
    /**
     * 用户退出登录的接口
     * 资源：/sessions
     * 动作：DELETE
     */
    @DeleteMapping
    public void deleteSession(HttpSession session, HttpServletResponse resp){
        //用户访问的时候就销毁当前的session
        session.invalidate();
        //销毁之后就响应204这个状态给浏览器
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
